package com.example.test.accountinfoa.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.test.accountinfoa.dao.AccountInfoDao;
import com.example.test.accountinfoa.fegin.Bank2Client;
import com.example.test.accountinfoa.pojo.AccountChangeEvent;
import com.example.test.accountinfoa.service.AccountInfoService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountInfoServiceImpl implements AccountInfoService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private AccountInfoDao accountInfoDao;


    @Override
    @Transactional
    public void updateAccountBalance(AccountChangeEvent accountChangeEvent) {

//        冪等判斷
        if (accountInfoDao.isExistTx(accountChangeEvent.getTxNo())>0){
            return;
        }
        // 扣减金额
        accountInfoDao.updateAccountBalance(accountChangeEvent.getAmount()*-1,accountChangeEvent.getAccountNo());
        // 添加日志
        accountInfoDao.addTx(accountChangeEvent.getTxNo());
    }

    @Override
    public void sendupdateAccountBalance(AccountChangeEvent accountChangeEvent) {
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("accountChange",accountChangeEvent);
        String json=jsonObject.toJSONString();
        Message<String> build = MessageBuilder.withPayload(json).build();

        rocketMQTemplate.sendMessageInTransaction("producer_group_txmsg_bank1","topic_txmsg",build,null);
    }
}
